package com.zyg.optional;

import com.zyg.pojo.Account;
import com.zyg.pojo.User;

import java.util.Optional;

/**
 * optional相关api
 */
public class OptionalDemo {
    public static void main(String[] args) {
        User user = new User(1, "张三", 18, true, 80);
        String userName = getUserName(user);
        System.out.println(userName);
        Account account = new Account(1L, "lisi", "123456");
        User user2 = new User(2, "李四", 20, false, 90,account);
        String userName2 = getUserNameFlatMap(user);
        System.out.println(userName2);
    }

    private static String getUserName(User user) {
        Optional<User> optional1 = Optional.ofNullable(user);
        if (optional1.isPresent()) {
            return optional1.get().getName();
        }
        return "";
    }


    private static String getUserNameFlatMap(User user) {
        //orElse和orElseGet的区别在于后者是采用延迟加载的方式
        String userName = Optional.ofNullable(user).flatMap(user1 -> Optional.ofNullable(user1.getAccount())).map(Account::getUserName).orElse("");
        //String userName = Optional.ofNullable(user).flatMap(user1 -> Optional.ofNullable(user1.getAccount())).map(Account::getUserName).orElseGet(()->"无");
        //Optional<String> stringOptional = Optional.ofNullable(user).flatMap(user1 -> Optional.ofNullable(user1.getAccount())).map(Account::getUserName);
        //Optional.ofNullable(user).flatMap(user1 -> Optional.ofNullable(user1.getAccount())).map(Account::getUserName).orElseThrow(NullPointerException::new);
        return userName;
    }

}
